import React, { Component } from 'react';
// 引入echarts主模块
// @ts-ignore
import * as echarts from 'echarts';
import ReactEcharts from 'echarts-for-react';
import { getNodesLines } from '@/services/points';
import { transCoord } from './coordTransForm';
import mockdata from './mockdata';

require('echarts/extension/bmap/bmap');
require('echarts/map/js/china.js');

interface IMapViewProps {
  loading?: boolean;
}
interface IMapData {
  points: any[];
  lines: any[];
}

// interface IPoint {
//   id: number;
//   name: string;
//   point: number[];
// }
// interface ILine {
//   id: number;
//   coords: number[];
//   lineStyle: any
// }
interface IMapViewState {
  windowHeight: number;
  mdata: IMapData;
}

class MapView extends Component<IMapViewProps, IMapViewState> {
  state: IMapViewState = {
    windowHeight: 0,
    mdata: {
      points: [],
      lines: [],
    },
  };

  mapInstance = null;

  componentDidMount() {
    this.updateDimensions();
    window.addEventListener('resize', this.updateDimensions);
    getNodesLines().then((res) => {
      if (res) {
        const data = res;
        const nodes: any[] = [];
        const lines: any[] = [];
        const resultLines: any[] = [];
        // @ts-ignore
        data.forEach((item: any) => {
          if (item.type === 'node') {
            nodes.push({
              id: item.id,
              name: item.properties.name,
              point: transCoord(
                item.properties.coordinates.longitude,
                item.properties.coordinates.latitude,
              ), // 将wgs-84坐标转换成百度坐标系
            });
          } else if (item.type === 'relationship') {
            lines.push({
              id: item.id,
              start: item.start.id,
              end: item.end.id,
            });
          }
        });
        lines.forEach((line: any) => {
          const parr = [];
          const start = nodes.find((item) => item.id === line.start).point;
          const end = nodes.find((item) => item.id === line.end).point;
          parr[0] = start;
          parr[1] = end;
          resultLines.push({
            coords: parr,
            id: line.id,
          });
        });
        this.setState({
          mdata: {
            points: nodes,
            lines: resultLines,
          },
        });
      }
    });
  }

  componentWillUnmount() {}

  getOption = () => {
    const { mdata } = this.state;
    // @ts-ignore
    const sdata = mdata.points.map((item) => {
      return {
        name: item.name,
        value: item.point,
      };
    });
    const hStep = 300 / (mockdata.plists.length - 1);
    // @ts-ignore
    const busLines = [
      ...mockdata.plists.map((busLine, idx) => {
        let prevPt;
        const ps = [];
        for (let i = 0; i < busLine.length; i += 2) {
          let pt = [busLine[i], busLine[i + 1]];
          if (i > 0) {
            // @ts-ignore
            pt = [
              // @ts-ignore
              prevPt[0] + pt[0],
              // @ts-ignore
              prevPt[1] + pt[1],
            ];
          }
          prevPt = pt;
          ps.push([pt[0] / 1e4, pt[1] / 1e4]);
        }
        return {
          coords: ps,
          lineStyle: {
            normal: {
              color: echarts.color.modifyHSL('#5A94DF', Math.round(hStep * idx)),
            },
          },
        };
      }),
    ];
    const addLines = [
      ...mdata.lines.map((addline, idx) => {
        return {
          coords: addline.coords,
          lineStyle: {
            normal: {
              color: echarts.color.modifyHSL('#5A94DF', Math.round(hStep * idx)),
            },
          },
        };
      }),
    ];
    const opts = {
      bmap: {
        center: [121.555514, 30.008775],
        zoom: 13,
        roam: true,
        mapStyle: {
          styleJson: [
            {
              featureType: 'water',
              elementType: 'all',
              stylers: {
                color: '#031628',
              },
            },
            {
              featureType: 'land',
              elementType: 'geometry',
              stylers: {
                color: '#000102',
              },
            },
            {
              featureType: 'highway',
              elementType: 'all',
              stylers: {
                visibility: 'off',
              },
            },
            {
              featureType: 'arterial',
              elementType: 'geometry.fill',
              stylers: {
                color: '#000000',
              },
            },
            {
              featureType: 'arterial',
              elementType: 'geometry.stroke',
              stylers: {
                color: '#0b3d51',
              },
            },
            {
              featureType: 'local',
              elementType: 'geometry',
              stylers: {
                color: '#000000',
              },
            },
            {
              featureType: 'railway',
              elementType: 'geometry.fill',
              stylers: {
                color: '#000000',
              },
            },
            {
              featureType: 'railway',
              elementType: 'geometry.stroke',
              stylers: {
                color: '#08304b',
              },
            },
            {
              featureType: 'subway',
              elementType: 'geometry',
              stylers: {
                lightness: -70,
              },
            },
            {
              featureType: 'building',
              elementType: 'geometry.fill',
              stylers: {
                color: '#000000',
              },
            },
            {
              featureType: 'all',
              elementType: 'labels.text.fill',
              stylers: {
                color: '#857f7f',
              },
            },
            {
              featureType: 'all',
              elementType: 'labels.text.stroke',
              stylers: {
                color: '#000000',
              },
            },
            {
              featureType: 'building',
              elementType: 'geometry',
              stylers: {
                color: '#022338',
              },
            },
            {
              featureType: 'green',
              elementType: 'geometry',
              stylers: {
                color: '#062032',
              },
            },
            {
              featureType: 'boundary',
              elementType: 'all',
              stylers: {
                color: '#465b6c',
              },
            },
            {
              featureType: 'manmade',
              elementType: 'all',
              stylers: {
                color: '#022338',
              },
            },
            {
              featureType: 'label',
              elementType: 'all',
              stylers: {
                visibility: 'off',
              },
            },
          ],
        },
      },
      series: [
        {
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: sdata,
          showAllSymbol: true,
          symbolSize: 20,
          itemStyle: {
            color: 'rgb(255, 249, 0)',
          },
          label: {
            normal: {
              show: true,
              position: 'right',
              formatter: '{b}',
            },
          },
          symbol:
            'path://M6648.65-3390.8l-4.149,5.028.86,12.027-1.95,2.294v3.709l2.944,1.415v3.174h10.153l2.523-2.084v-3.594h-2.523v-4.914l-1.53-2.524v-9.5Z',
        },
        {
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: busLines,
          silent: true,
          lineStyle: {
            opacity: 1,
            width: 1,
          },
          progressiveThreshold: 500,
          progressive: 200,
        },
        {
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: busLines,
          lineStyle: {
            width: 0,
          },
          effect: {
            constantSpeed: 20,
            show: true,
            trailLength: 0.1,
            symbolSize: 1.5,
          },
          zlevel: 1,
        },
        {
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: addLines,
          silent: true,
          lineStyle: {
            opacity: 1,
            width: 1,
          },
          progressiveThreshold: 500,
          progressive: 200,
        },
        {
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: addLines,
          lineStyle: {
            width: 0,
          },
          effect: {
            constantSpeed: 20,
            show: true,
            trailLength: 0.1,
            symbolSize: 4,
          },
          zlevel: 1,
        },
      ],
    };
    return opts;
  };

  updateDimensions = () => {
    this.setState({ windowHeight: window.innerHeight });
  };

  render() {
    const { windowHeight } = this.state;
    return (
      <div
        style={{ width: '100%', height: windowHeight - 64, position: 'relative' }}
        className="mapview"
      >
        <ReactEcharts option={this.getOption()} notMerge lazyUpdate style={{ height: '100%' }} />
      </div>
    );
  }
}

export default MapView;
